<?php

namespace Modules\Card\Entities;

use Modules\Core\Entities\BaseEntity as Model;

use Modules\Card\Entities\Card;

use ThrowException;

class CardAsset extends Model
{
    protected $guarded = [];
    protected $table = 'card_assets';
    static public $resourceName = '';

    public function records()
    {
        return $this->hasMany('\Modules\Card\Entities\CardAssetRecord', 'card_asset_id');
    }

    // public function getBalanceAttribute($value)
    // {
    //     // return $this->mapActivityType($type);
    // }

    // public function setBalanceAttribute($value)
    // {
    //     // $this->activity_type = $this->mapActivityType($type);
    //     $this->attributes['activity_type'] = $this->mapActivityType($value);
    // }

    protected function change($type, $value, $options)
    {
        if ($type === 0 && $this->balance < $value)
            return false;

        $before = $this->balance;

        $this->balance += $value * ($type === 0 ? -1 : 1);;

        $this->save();

        $after = $this->balance;

        $this->records()->create([
            'uuid' => uniqid(),
            'order_id' => @($options['order_id']),
            'before' => $before,
            'after' => $after,
            'value' => $value,
            'type' => $type,
            'description' => @v($options['description'])
        ]);

        return true;
    }

    public function in($value, $options = [])
    {
        return $this->change(1, $value, $options);
    }

    public function out($value, $options = [])
    {
        return $this->change(0, $value, $options);
    }

    public function use($total, $options) 
    {
        $flag = $this->out($total, $options);

        // 扣除成功
        if ($flag) {
            Card::addUsedCountByType($this->type, $total);
        }

        return $flag;
    }
}
